//
//  WXAssetsPicker.m
//  Component
//
//  Created by Andy_chen on 16/4/8.
//  Copyright © 2016年 Andycchen. All rights reserved.
//

#import "WXAssetsPicker.h"
#import "WXAsset.h"
#import "WXImageCell.h"
#import "WXPreviewController.h"
#import "WXAssetSelectionDelegate.h"
#import "WXImagePickerController.h"

@interface WXAssetsPicker ()<UICollectionViewDataSource, UICollectionViewDelegate,WXAssetSelectionDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong)NSMutableArray *assets;
@property (nonatomic, strong)NSMutableArray *selectedAssets;
@property (nonatomic, assign)NSInteger sectionCount;

@end

@implementation WXAssetsPicker
#pragma mark - life cycle

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setToolbarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    [self setUpSubViews];
    
    [self performSelector:@selector(loadData) withObject:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - pravite mothed

- (void)setUpSubViews {
    
    //navigation
    [self.navigationItem setTitle:@"照片"];
    
    //navigaitonBar
    UIButton *leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 36)];
    [leftButton setImage:[UIImage imageNamed:@"barbuttonicon_back"] forState:UIControlStateNormal];
    [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -1, 0, 0)];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [leftButton addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self.navigationItem setLeftBarButtonItem:backButton];
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 36, 36)];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [rightButton addTarget:self action:@selector(cancelImagePicker) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self.navigationItem setRightBarButtonItem:cancelButton];
    
    //ToolBar
    [self.navigationController setToolbarHidden:NO];
  
    
    UIButton *previewButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 36)];
    [previewButton setTitle:@"预览" forState:UIControlStateNormal];
    [previewButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [previewButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [previewButton addTarget:self action:@selector(previewAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *previewBtn = [[UIBarButtonItem alloc] initWithCustomView:previewButton];
    previewBtn.enabled = NO;

    UIButton *sendButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 36)];
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    [sendButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
 
    [sendButton addTarget:self action:@selector(sendImagesAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *sendBtn = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    UIBarButtonItem *emptyBtn =     [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    sendBtn.enabled = NO;
    sendButton.alpha = 0.6;
    NSArray *items = @[previewBtn,emptyBtn,emptyBtn,emptyBtn,sendBtn];
    
    [self setToolbarItems:items animated:YES];
    
}

- (void)goback {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cancelImagePicker {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)previewAction:(id)sender {
    
    NSLog(@"preview");
}

- (void)sendImagesAction:(id)sender {
    
    NSLog(@"send");
}

- (void)showSelectButtonAnimation:(UIView *)view {
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    
    animation.duration = 0.2;
    animation.repeatCount = 1;
    animation.autoreverses = YES;
    
    animation.fromValue = [NSNumber numberWithFloat:1.2];
    animation.toValue = [NSNumber numberWithFloat:1.0];
    
    [view.layer addAnimation:animation forKey:@"scale-layer"];
}

- (void)loadData {
    
    _assets = [[NSMutableArray alloc]initWithCapacity:0];
    _selectedAssets = [[NSMutableArray alloc]initWithCapacity:0];
    
    @autoreleasepool {
        [self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            
            if (!result) {
                return ;
            }
            WXAsset *asset = [[WXAsset alloc]initWithAsset:result];
            asset.index = index;
            [_assets addObject:asset];
        }];
        
        _sectionCount = _assets.count%4>0?(_assets.count/4+1):(_assets.count/4);
        
        //刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (_assets.count > 0) {
                
                NSInteger row = _assets.count%4 - 1;
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:_sectionCount-1];
                
                //滚动到底部
                [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionBottom
                                                    animated:YES];
            }
        });
    }
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger number = 0;
    if (_sectionCount == 0 || _sectionCount == 1) {
        number = _assets.count%4;
    }
    else {
        number = (section==_sectionCount-1)?_assets.count%4:4;
    }
    
    return number;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WXImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
    cell.asset = [_assets objectAtIndex:(indexPath.row + indexPath.section*4)];
    cell.delegate = self;
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return _sectionCount;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
//    WXPreviewController *previewController = [[UIStoryboard storyboardWithName:@"Picker" bundle:[NSBundle mainBundle]]instantiateViewControllerWithIdentifier:@"preview"];
//    //隐藏导航栏
//    [self.navigationController setNavigationBarHidden:YES];
//    [self.navigationController pushViewController:previewController animated:YES];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = self.view.frame.size.width;
    CGFloat value = (width - 5*5)/4;
    
    return CGSizeMake(value, value);
}

#pragma mark - WXAssetSelectionDelegate
- (BOOL)shouldSelectAsset:(WXAsset *)asset previousCount:(NSUInteger)previousCount {
    
    BOOL result = NO;
    
    WXImagePickerController *picker = (WXImagePickerController *)self.navigationController;
    
    if(_selectedAssets.count < picker.maximumImagesCount) {
      [_selectedAssets addObject:asset];
      result = YES;
    }
    else {
        NSString *massage = [NSString stringWithFormat:@"最多只能选择%ld张照片",picker.maximumImagesCount];
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@""
                                                           message:massage
                                                          delegate:self
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil, nil];
        [alertView show];
    }
    
    return result;
}

- (void)shouldDeselectAsset:(WXAsset *)asset previousCount:(NSUInteger)previousCount {

    [_selectedAssets removeObject:asset];

}

#pragma mark - setter and getter



@end
